package com.ssm.changeunit.console.parser;


import com.ssm.changeunit.command.*;
import org.apache.commons.cli.*;
import org.apache.log4j.Logger;

// <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
// #[regen=yes,id=DCE.47D6DC48-E235-2206-98F8-B3E8CD29B138]
// </editor-fold> 
public class BranchConsoleParser extends ConsoleParser {
    
    private static final Logger logger = Logger.getLogger(BranchConsoleParser.class);
    
    @Override
    public CommandWorkerOptions parse(java.lang.String[] userCommand) throws ConsoleParseException {
      try {
            // 파서 생성
            CommandLineParser parser = new GnuParser();

            Options options = new Options();

            Option typeOption = OptionBuilder.withLongOpt("type").hasArgs().isRequired().create();
            Option nameOption = OptionBuilder.withLongOpt("name").hasArgs().create();

            options.addOption(typeOption);
            options.addOption(nameOption);

            CommandLine commandLine = parser.parse(options, userCommand);

            CommandWorkerOptions commandWorkerOptions = new CommandWorkerOptions();

            // type 프로퍼티가 있는지 검사
            if(commandLine.hasOption("type")) {

                CommandWorkerOption commandWorkerOption = new CommandWorkerOption("type");
                commandWorkerOptions.addCommandWorkerOption(commandWorkerOption);

                String[] items = commandLine.getOptionValues("type");
                logger.debug("type :"+items[0]+"\n");
                
                if(!(items[0].toLowerCase().equals("add")||items[0].toLowerCase().equals("delete")||items[0].toLowerCase().equals("list"))){
                    // 에러 발생
                    throw new ConsoleParseException("type 프로퍼티가 값이 올바르지 않습니다.");
                }
                    
                commandWorkerOption.addValue(items[0]);

                // name 프로퍼티가 있는지 검사
                if(commandLine.hasOption("name")) {
                    CommandWorkerOption commandWorkerOption2 = new CommandWorkerOption("name");

                    String[] items2 = commandLine.getOptionValues("name");
                    logger.debug("name :"+items2[0]);
                    commandWorkerOption2.addValue(items2[0]);

                    commandWorkerOptions.addCommandWorkerOption(commandWorkerOption2);

                }else {
                    logger.debug("name 프로퍼티가 존재하지 않습니다.");
                }
            }
            else {
                // 에러 발생
                logger.debug("type 프로퍼티가 존재하지 않습니다.");
                throw new ConsoleParseException("type 프로퍼티가 존재하지 않습니다.");
            }

            return commandWorkerOptions;
            
        }
        catch(ParseException ex) {
            throw new ConsoleParseException(ex);
        }
    }
}

